# 使用重入锁（Rlock）控制线程的进行,同一个线程可以多次获得重入锁,重入锁的释放只能由获得其的线程释放
import threading
import time
import random


class Box:
    def __init__(self):
        self.lock = threading.RLock()  # 这样使得锁一直是释放状态，每次调用都获得一个资源，然后释放
        self.total_items = 0

    def excute(self, value):
        with self.lock:
            self.total_items += value

    def add(self):
        with self.lock:
            self.excute(1)

    def remove(self):
        with self.lock:
            self.excute(-1)


def adder(box, items):
    print('N {} items to ADD\n'.format(items))
    while items:
        box.add()
        time.sleep(1)
        items -= 1
        print("ADDED one item --->{} item to ADD\n".format(items))


def remover(box, items):
    print('N {} items to REMOVE\n'.format(items))
    while items:
        box.remove()
        time.sleep(1)
        items -= 1
        print("REMOVED one item --->{} item to REMOVE\n".format(items))


def main():
    items = 10
    box = Box()
    t1 = threading.Thread(target=adder, args=(box, random.randint(10, 20)))
    t2 = threading.Thread(target=remover, args=(box, random.randint(1, 10)))
    t1.start()
    t2.start()

    t1.join()
    t2.join()


# 线程1获得锁，线程2获得锁，线程1释放锁，线程2释放锁
if __name__ == '__main__':
    main()
